package com.bdmc.smokesensor.controller;

import java.util.List;
import java.util.Map;

import com.bdmc.smokesensor.Utils.Msg;
import com.bdmc.smokesensor.Utils.ResultUtil;
import com.bdmc.smokesensor.entity.Smk_Maintenance;
import com.bdmc.smokesensor.entity.Sys_Log;
import com.bdmc.smokesensor.services.Smk_MaintenanceService;
import com.bdmc.smokesensor.services.Sys_UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/mtc", method = RequestMethod.POST)
public class Smk_MaintenanceController extends BaseController {

    @Autowired
    private Smk_MaintenanceService _mainSvs;

    @RequestMapping(value = "/list")
    public Msg list(@RequestBody Map<String, Object> reqMap) {
        int page = Integer.parseInt(reqMap.get("page").toString());
        int rows = Integer.parseInt(reqMap.get("rows").toString());
        int dep_id = Integer.valueOf(request.getAttribute("dep_id").toString());
        String mainName = reqMap.get("mainName").toString();
        Map<String, Object> map = _mainSvs.getCurrentMainten(dep_id, mainName, PageRequest.of(page, rows));
        return ResultUtil.success(map);
    }

    @RequestMapping(value = "/combo")
    public Msg combo() {
        int dep_id = Integer.valueOf(request.getAttribute("dep_id").toString());
        List<Map<String, Object>> map = _mainSvs.getCurrentCombo(dep_id);
        return ResultUtil.success(map);
    }

    /**
     * 数据新增或更新，save方法可以执行添加也可以执行更新，如果需要执行持久化的实体存在主键值则更新数据，如果不存在则添加数据。
     */

    @RequestMapping(value = "/save")
    public Msg save(@RequestBody Smk_Maintenance main) {
        String action = main.getId() > 0 ? "修改:" : "新增:";
        try {
            Smk_Maintenance m = _mainSvs.save(main);
            if (m != null && m.getId() > 0) {
                Sys_Log log = new Sys_Log(getLoginName(), getLocalIp(), "维保单位", action + m.getMainName());
                _logSvs.save(log);
                return ResultUtil.success();
            } else {
                return ResultUtil.error(-1, "操作失败，请联系管理员。");
            }
        } catch (DataIntegrityViolationException e) {
            logger.error(e.getMessage());
            return ResultUtil.error(-1, "维保单位名称重复。");
        }

    }

    @RequestMapping(value = "/delete")
    public Msg delete(@RequestBody Map<String, Integer> map) {
        int id = map.get("id");
        _mainSvs.deleteById(id);
        Sys_Log log = new Sys_Log(getLoginName(), getLocalIp(), "维保单位", "删除：" + id);
        _logSvs.save(log);
        return ResultUtil.success();
    }
}